import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { TreeSelectC } from '../../form';

class FundApplicationIndustryC extends React.Component {
  constructor() {
    super();
    this.state = {
      dataSource: [],
      treeExpandedKeys: [],
      defaultExpandKeys: [],
    };
  }

  // 默认值
  static defaultProps = {
    showSearch: true, // 默认进入模糊搜索
    initialValue: undefined, // 初始值
    title: '资金运用行业',
    treeNodeFilterProp: 'title',
    onRef: () => {}, // 本组件的引用
    onChangeFn: () => {}, // 改变
    setSelect: () => {}, // 塞值
    reset: () => {}, // 重置
    getInfo: () => {}, // 获取表单中的值
    placeholder: '请选择',
    rules: undefined,
    parentCanClick: false, // 父节点是否可以点击
    disabled: false, // 是否禁用
    allowClear: false,
    OnlySupportFirstLevel: false, // 是否只使用一级数据
  };

  componentDidMount() {
    this.props.onRef && this.props.onRef(this);
    const {
      globalM: {
        dataDictionary: { GJTJJHYFLI = [] },
      },
      OnlySupportFirstLevel,
      parentCanClick,
    } = this.props;
    let newArr = [];
    if (GJTJJHYFLI && GJTJJHYFLI.length) {
      newArr = GJTJJHYFLI.map((item) => {
        const obj = {
          title: item.value,
          value: item.code,
          key: item.code,
        };
        // 这边需要处理数据变成父节点不可以点击
        if (!parentCanClick) {
          obj.selectable = false;
        }
        // 是否只使用一级数据
        if (!OnlySupportFirstLevel) {
          obj.children = item?.children.map((x) => {
            return {
              value: x.code,
              title: `${x.code}-${x.value}`,
              key: x.code,
            };
          });
        }
        return obj;
      });
    }
    // eslint-disable-next-line react/no-did-mount-set-state
    this.setState(
      {
        dataSource: newArr,
      },
      () => {
        // 当初始化有值的时候 需要将初始化中父元素的值存储
        const datas = _.cloneDeep(this.state.dataSource);
        const parentKey = null;
        const parentGetByKeys = []; // 此时要展开的值
        this.findParentKey(this.props.initialValue, datas, parentKey, parentGetByKeys, true);
        this.setState({
          defaultExpandKeys: parentGetByKeys,
          treeExpandedKeys: parentGetByKeys,
        });
      },
    );
  }

  // 进行塞值
  setSelect = (value) => {
    const valueF = {};
    valueF[this.props.dataIndex] = value;
    this.props.form.setFieldsValue(valueF);
  };

  // 重置
  reset = () => {
    const { dataIndex, form } = this.props;
    form.resetFields([dataIndex]);
  };

  // 获取表单的值
  // getInfo = () => {
  //   const { validateFieldsAndScroll } = this.props.form;
  //   let query;
  //   validateFieldsAndScroll((err, fieldsValue) => {
  //     if (!err) {
  //       query = fieldsValue;
  //     }
  //   });
  //   return query;
  // };

  // 获取表单的值
  getInfo = async () => {
    try {
      await this.props.form.validateFields();
      const fieldsValue = this.props.form.getFieldsValue();
      let query;
      return (query = fieldsValue);
    } catch (err) {
      this.onFinishFailed(err);
    }
  };

  onFinishFailed = ({ errorFields }) => {
    const { scrollToField } = this.props.form;
    scrollToField(errorFields[0].name);
  };

  // 通过key找父节点
  findParentKey = (initialValue, data, parentKey, parentGetByKeys, flag) => {
    // 如果初始值是父级 如果初始值是子集
    if (data && data.length) {
      for (let i = 0; i < data.length; i++) {
        if (flag) {
          // eslint-disable-next-line no-param-reassign
          parentKey = null;
        }
        if (initialValue == data[i].value) {
          if (flag) {
            parentGetByKeys.push(data[i].value);
          } else {
            parentGetByKeys.push(parentKey);
          }
        } else {
          // 此时不是父级
          // eslint-disable-next-line no-lonely-if
          if (data[i].children && data[i].children.length) {
            // eslint-disable-next-line max-depth, no-param-reassign
            if (flag) parentKey = data[i].value;
            this.findParentKey(initialValue, data[i].children, parentKey, parentGetByKeys, false);
          }
        }
      }
    }
    return parentGetByKeys;
  };

  // 通过输入值找父节点
  findParentValue = (inputs, datas, parentKey, parentGetByKeys, flag) => {
    if (datas && datas.length > 0) {
      for (let j = 0; j < datas.length; j++) {
        if (flag) {
          // eslint-disable-next-line no-param-reassign
          parentKey = null;
        }
        if (datas[j].title.indexOf(inputs) >= 0) {
          if (flag) {
            parentGetByKeys.push(datas[j].value);
          } else {
            parentGetByKeys.push(parentKey);
          }
        } else {
          // 此时是子集
          // eslint-disable-next-line no-lonely-if
          if (datas[j].children && datas[j].children.length) {
            // eslint-disable-next-line max-depth, no-param-reassign
            if (flag) parentKey = datas[j].value;
            this.findParentValue(inputs, datas[j].children, parentKey, parentGetByKeys, false);
          }
        }
      }
    }
  };

  // 进行模糊搜索
  onSearch = (e) => {
    if (!e) {
      this.setState((prevState) => ({ treeExpandedKeys: prevState.defaultExpandKeys }));
    } else {
      // 否则则对输入值进行过滤
      const datas = _.cloneDeep(this.state.dataSource);
      const parentKey = null;
      const parentGetByKeys = []; // 此时要展开的值
      this.findParentValue(e, datas, parentKey, parentGetByKeys, true);
      this.setState({
        treeExpandedKeys: parentGetByKeys,
      });
    }
  };

  onTreeExpand = (expandedKeys) => {
    this.setState({
      treeExpandedKeys: expandedKeys,
    });
  };

  // 改变的时候初始化的值需要变成 选择的值
  changeValue = (e, option) => {
    // 这个是选择的子集
    const datas = _.cloneDeep(this.state.dataSource);
    const parentKey = null;
    const parentGetByKeys = []; // 此时要展开的值
    this.findParentKey(e, datas, parentKey, parentGetByKeys, true);
    this.setState(
      {
        defaultExpandKeys: parentGetByKeys,
        treeExpandedKeys: [...parentGetByKeys],
      },
      () => {
        this.props.onChangeFn && this.props.onChangeFn(e, option);
      },
    );
  };

  render() {
    const { dataSource, treeExpandedKeys, defaultExpandKeys } = this.state;
    const { formItemLayout, form, labalWrap, title, dataIndex, allowClear, disabled, placeholder, initialValue, rules } = this.props;
    return (
      <TreeSelectC
        dataIndex={dataIndex}
        title={title}
        form={form}
        // treeNodeFilterProp='title'
        showSearch={true}
        formItemLayout={formItemLayout}
        labalWrap={labalWrap}
        placeholder={placeholder}
        initialValue={initialValue}
        allowClear={allowClear}
        onChange={(e) => this.changeValue(e)}
        dataSource={dataSource}
        rules={rules}
        onSearch={this.onSearch}
        treeExpandedKeys={treeExpandedKeys}
        treeDefaultExpandedKeys={defaultExpandKeys}
        disabled={disabled}
        onTreeExpand={this.onTreeExpand}
        {...this.props}
      />
    );
  }
}

// props默认值
FundApplicationIndustryC.propsTypes = {
  showSearch: PropTypes.bool, // 是否展示搜索，默认展示
  title: PropTypes.string, // 这个是表单名称
  dataIndex: PropTypes.string, // 表单基于字段拿值
  treeNodeFilterProp: PropTypes.string, // 这个是showSearch得时候过滤依据
  formItemLayout: PropTypes.object, // 样式布局
  labalWrap: PropTypes.bool, // 是否标题换行
  value: PropTypes.string, // 选中值
  placeholder: PropTypes.string, // 占位符
  initialValue: PropTypes.string, // 默认值
  rules: PropTypes.array, // 校验
  disabled: PropTypes.bool, // 是否禁用
  parentCanClick: PropTypes.bool, // 父节点是否可以点击
  OnlySupportFirstLevel: PropTypes.bool, // 是否只用一级数据
};

export default connect(({ globalM }) => ({ globalM }))(FundApplicationIndustryC);
